package com.ficus.road.maintain.handler.smartdecision.handlers.highway;

import com.ficus.road.maintain.core.model.smartnew.*;
import com.ficus.road.maintain.dao.smartnew.SmartHighwayDao;
import com.ficus.road.maintain.dao.smartnew.SmartTableMergedDao;
import com.ficus.road.maintain.dao.smartnew.SmartTableUnmergedDao;
import com.ficus.road.maintain.handler.smartdecision.ReserveMerger;
import com.ficus.road.maintain.handler.smartdecision.TableMerger;
import com.ficus.road.maintain.handler.smartdecision.enums.SmartDecisionStrategyEnum;
import com.google.common.base.Objects;
import lombok.RequiredArgsConstructor;
import org.springframework.core.annotation.Order;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @author xiawen yang
 * @date 2022/7/20 下午8:23
 */
@Component
@Order(2)
@RequiredArgsConstructor
public class SmartDecisionHighwaySortingHandler extends AbstractSmartDecisionHighwayHandler {

    private static final SmartDecisionStrategyEnum STRATEGY = SmartDecisionStrategyEnum.HIGHWAY_SORTING;
    private static final String IS_FINAL_RESULT = "是";
    private final SmartHighwayDao smartHighwayDao;
    private final SmartTableMergedDao smartTableMergedDao;
    private final SmartTableUnmergedDao smartTableUnmergedDao;
    private final TableMerger tableMerger;
    private final ReserveMerger reserveMerger;

    @Override
    public SmartDecisionResponse doHandle(SmartDecisionRequest request, SmartDecisionResponse response) {
        SmartDecisionHighwayRequest highwayRequest = (SmartDecisionHighwayRequest) request;
        preProcess(highwayRequest, response);
        response = strategySmartDecisionService.smartDecisionCalculate(STRATEGY, highwayRequest.getParams(), response);
        postProcess(response);
        return response;
    }

    private void buildParams(SmartDecisionHighwayRequest request, SmartDecisionResponse response) {
        // 工程项目进入智能排序阶段
        System.out.println("SmartSortingHandler's projectIds: " + response.getSmartInspectionResponse().getProjectIds());
        List<SmartDecisionExcelVO> params = smartHighwayDao.findByQuery(new Query(Criteria.where("_id").in(response.getSmartInspectionResponse().getProjectIds())));
        request.setParams(params);
    }

    /**
     * 前处理：
     * 找出工程项目列表作为参数
     *
     * @param request
     * @param response
     */
    private void preProcess(SmartDecisionHighwayRequest request, SmartDecisionResponse response) {
        buildParams(request, response);
    }

    /**
     * 后处理:
     * 过滤非最终结果
     * 合并排分表
     * 合并储备库
     * 智能排序相关统计
     * 保存排分表(储备库暂时没有存到数据库)
     */
    private void postProcess(SmartDecisionResponse response) {
        SmartDecisionResponse.SmartSortingResponse smartSortingResponse = response.getSmartSortingResponse();
        // 过滤非最终结果
        List<SmartTable> tablesBeforeMerged = smartSortingResponse.getTablesBeforeMerge();
//        List<SmartTable> tablesBeforeMerged = smartSortingResponse.getTablesBeforeMerge().stream().filter(item -> Objects.equal(IS_FINAL_RESULT, item.getIsFinalResult())).collect(Collectors.toList());
        smartSortingResponse.setTablesBeforeMerge(tablesBeforeMerged);
        // 合并排分表
        smartSortingResponse.setTablesAfterMerge(tableMerger.merge(smartSortingResponse.getTablesBeforeMerge()));
        // 合并储备库
        smartSortingResponse.setReservesAfterMerged(reserveMerger.merge(smartSortingResponse.getReservesBeforeMerged()));
        // 智能排序相关统计
        calculateTypeCount(response);
        // 保存排分表和储备库
        saveSmartTable(response);
    }

    public void calculateTypeCount(SmartDecisionResponse response) {
        List<SmartTable> smartTables = response.getSmartSortingResponse().getTablesBeforeMerge();
        SmartDecisionResponse.SmartSortingResponse smartSortingResponse = response.getSmartSortingResponse();
        smartSortingResponse.setType1((int) smartTables.stream().filter(item -> Objects.equal(item.getType(), "第一大类")).count());
        smartSortingResponse.setType2((int) smartTables.stream().filter(item -> Objects.equal(item.getType(), "第二大类")).count());
        smartSortingResponse.setType3((int) smartTables.stream().filter(item -> Objects.equal(item.getType(), "第三大类")).count());
        smartSortingResponse.setType4((int) smartTables.stream().filter(item -> Objects.equal(item.getType(), "第四大类")).count());
        smartSortingResponse.setType5((int) smartTables.stream().filter(item -> Objects.equal(item.getType(), "第五大类")).count());
        smartSortingResponse.setType6(response.getSmartSortingResponse().getReservesBeforeMerged().size());
    }

    public void saveSmartTable(SmartDecisionResponse response) {
        List<SmartTable> mergedTables = response.getSmartSortingResponse().getTablesAfterMerge();
//        List<SmartTable> mergedTablesByChange = mergedTables.stream().map(SmartTable::convertMergeTableBySource).collect(Collectors.toList());
//        response.getSmartSortingResponse().setTablesAfterMerge(mergedTablesByChange);
        mergedTables.forEach(smartTableMergedDao::saveOrUpdate);
        List<SmartTable> unmergedTables = response.getSmartSortingResponse().getTablesBeforeMerge();
        unmergedTables.forEach(smartTableUnmergedDao::saveOrUpdate);
    }
}
